<template>
  <div>
    <v-form-render
      v-show="hasControls"
      ref="vFormRef"
      @form-change="onFormChange('vform')"
    >
    </v-form-render>

    <el-input
      v-show="!hasControls &&formData.length > 2"
      type="textarea"
      :rows="5"
      placeholder="表单json数据(key 和字符一定要双引号)"
      v-model="formData"
      @change="onFormChange('input')"
    ></el-input>
  </div>
</template>

<script setup>
import { reactive, ref, unref, nextTick, watch, computed } from "vue";
import formDataAdapter from "./formDataAdapter";

const emit = defineEmits(["form-change"]);

const vFormRef = ref(null);
const formData = ref({});
const hasControls = ref(false);
const designFramework = ref("");

const setDesignContent = (content, framework) => {
  designFramework.value = framework;
  if (content && content.length > 2) {
    if (framework !== "vform") { //vform
      const jsonData = formDataAdapter.defaultToVfrom(content);
      vFormRef.value.setFormJson(jsonData);
    }
     else {
      vFormRef.value.setFormJson(JSON.parse(content));
    }
    hasControls.value = true;
  } else {
    formData.value = "{}";
    hasControls.value = false;
  }
};

const setFormData = (data) => {
    if(hasControls.value){
        vFormRef.value.setFormData(data);
    }
    else{
        formData.value = JSON.stringify(data||{});
    }
};
const getFormData = async () => {
  let data = null;
  if (hasControls.value) {
    data = JSON.stringify(await vFormRef.value.getFormData());
  } else {
    data = formData.value;
  }
  return data;
};

const onFormChange = async () => {
  validateForm(async (valid) => {
    if (valid) {
      let data = await getFormData();
      emit("form-change", data);
    }
  });
};

const validateForm = async (callback) => {
  if (hasControls.value && vFormRef.value) {
    vFormRef.value.validateForm(async (valid) => {
      if (valid) {
        callback(valid);
      }
    });
  } else {
    callback(true);
  }
};

defineExpose({
  setDesignContent,
  setFormData,
  getFormData,
  validateForm,
});
</script>

<style></style>
